﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextToHTMLExtensionInterfaces;
using System.ComponentModel.Composition;

namespace YouTubeTranslator
{
    /// <summary>
    /// Given a simple youtube url, remap to an embeded video link.
    /// </summary>
    [Export(typeof(IRenderToHTML))]
    [ExportMetadata("type", typeof(Uri))]
    public class YouTubeMapper : IRenderToHTML
    {
        #region IRenderToHTML Members

        /// <summary>
        /// Look to see if we have youtube link (or not).
        /// </summary>
        /// <param name="objToRender"></param>
        /// <returns></returns>
        public bool CanRender(object objToRender)
        {
            Uri htmlLink = objToRender as Uri;
            if (htmlLink == null)
                return false;

            if (htmlLink.Host != "www.youtube.com")
                return false;

            return htmlLink.Query.Contains("v=")
                || htmlLink.AbsoluteUri.Contains("/v/");
        }

        /// <summary>
        /// Extract the key bit of information and put it in an embedable url.
        /// </summary>
        /// <param name="objToRender"></param>
        /// <returns></returns>
        public string Render(object objToRender)
        {
            Uri htmllink = objToRender as Uri;

            ///
            /// Extract the thing!
            /// 

            string videoID;
            int indexQ = htmllink.Query.IndexOf("v=");
            int indexL = htmllink.AbsoluteUri.IndexOf("/v/");
            if (indexQ >= 0)
            {
                videoID = ExtractVideoID(htmllink.Query.Substring(indexQ + 2));
            }
            else if (indexL >= 0)
            {
                videoID = ExtractVideoID(htmllink.AbsoluteUri.Substring(indexL + 3));
            }
            else
            {
                throw new ArgumentException("Bad URL for youtube!");
            }

            ///
            /// Build the embeded code
            /// 

            StringBuilder bld = new StringBuilder();
            bld.Append("<object width=\"560\" height=\"340\"><param name=\"movie\" value=\"http://www.youtube.com/v/");
            bld.Append(videoID);
            bld.Append("&hl=en&fs=1&\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/");
            bld.Append(videoID);
            bld.Append("&hl=en&fs=1&\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"560\" height=\"340\"></embed></object>");

            return bld.ToString();
        }

        /// <summary>
        /// Parse the input url string for the ID of the video.
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private string ExtractVideoID(string p)
        {
            int index = p.IndexOfAny(new char[] { '/', '?', '&', '#' });
            if (index < 0)
            {
                return p;
            }
            return p.Substring(0, index);
        }

        #endregion
    }
}
